$(function () {
  /*
   * 加载config
   */
  $.getJSON("/data/config.json" + "?r=" + Math.random(), function (data) {
    window.apis = data;
  });

  /*
   * flexslider组件
   * 所有可以左右切换的幻灯片、首页的左右滚动新闻等都有用到
   */
  $(".flexslider").each(function (index, element) {
    var _container = $(this);
    var _namespace = $(this).data("namespace");
    var _animation = $(this).data("animation") == "slide" ? "slide" : "fade";
    var _speed = $(this).data("speed") || 3000;
    var _duration = $(this).data("duration") || 1000;
    var _controlsContainer;
    var _controlNav = $(this).data("control-nav");
    var _directionNav = $(this).data("direction-nav") == true ? true : false;
    var _autoPlay = ($(this).data("autoplay") == true) ? true : false;
    var _loop = ($(this).data("loop") == true) ? true : false;
    var _hoverPause = ($(this).data("hover-pause") == true) ? true : false;
    var _width = $(this).innerWidth();

    if (_controlNav || _directionNav) {
      _controlsContainer = $(this).data("controls-container");
    }
    //console.log(_autoPlay,_controlNav, _directionNav, _controlsContainer);
    var options = {
      namespace: _namespace,
      animation: _animation,
      slideshow: _autoPlay,
      slideshowSpeed: _speed,
      animationSpeed: _duration,
      easing: "easeInOutExpo",
      pauseOnHover: _hoverPause,
      controlsContainer: _controlsContainer,
      controlNav: _controlNav,
      directionNav: _directionNav,
      prevText: _directionNav ? "<i class='icon-chevron-left'></i>" : '',
      nextText: _directionNav ? "<i class='icon-chevron-right'></i>" : '',
      animationLoop: _loop,
      useCSS: false,
      init: function () {
        _container.addClass("complete");
      }
    };
    //异步加载图片slider，在滚动到目标时加载图片
    if ($(this).find('.slides [data-src]').size() > 0) {
      options.after = renderPreview;
      options.start = renderPreview;
    }
    //首页横向滚动slider选项
    if ($(this).hasClass("flexslider-grid")) {
      options.animationLoop = false;
      options.itemWidth = 210;
      options.itemMargin = 0;
      options.minItems = getGridSize(); // use function to pull in initial value
      options.maxItems = getGridSize(); // use function to pull in initial value
    }
    //创建flexslider
    $(this).flexslider(options);
  });

  /*
   * 嵌入式视频播放器
   * 应用于媒体中心--视频，视频播放
   */
  //$("[data-toggle='video']").on("click",function(){
  $(".video-list").on("click","a",function(){
    var that = $(this),src = that.data('src');
    if ($(this).hasClass('p-m')) {
      if( !src ){
        alert('缺少data-src');
      return;
      }
    }
    else {
      return;
    }
    $("#embed-video-wrap iframe").attr('src',src).parent().addClass('active');
    return false;
  });
  $("#embed-video-wrap .close").on("click",function(){
    $("#embed-video-wrap").removeClass("active");
    setTimeout(function(){$("#embed-video-wrap iframe").attr('src','');},1000 );
  });

  /*
   * 地图组件
   * 应用于商店详情页，地图模块
   */
  $(".map-wrap").each(function () {
    var that = $(this);
    var wrap = that.attr("id");
    var city = that.data("city");
    var address = that.data("address");
    var pic = that.data("pic");
    var title = that.data("title") || "请为商家传入标题";
    title = "马可•波罗 "+title;
    var description = that.data("description") || "请为商家传入描述";
    var zoom = 16;
    var marker;
    var sContent = "<div class='map-infowindow'>" + "<h4>" + title + "</h4>" + "<img id='map-show-img' src='" + pic + "'/><p>" + description + "</p></div>";

    var content = '<div style="margin:0;line-height:20px;padding:2px;">' +
                  '<img src="'+pic+'" alt="" style="float:right;zoom:1;overflow:hidden;width:100px;height:100px;margin-left:3px;"/><p>'+ description +"</p></div>";

    // 百度地图API功能
    var map = new BMap.Map(wrap);
    var point = new BMap.Point(116.331398, 39.897445);
    map.centerAndZoom(point, zoom);
    //开启拖拽
    map.enableDragging();
    //禁用滚轮缩放
    map.disableScrollWheelZoom();
    //禁用地图拖拽
    //map.disableDragging();

    //右上角控件
    var top_right_navigation = new BMap.NavigationControl({
      anchor: BMAP_ANCHOR_TOP_RIGHT,
      type: BMAP_NAVIGATION_CONTROL_SMALL
    });
    //map.addControl(top_right_navigation);

    // 创建信息窗口对象
    var infoWindow = new BMap.InfoWindow(sContent);

    //创建检索信息窗口对象
    var searchInfoWindow = null;
     searchInfoWindow = new BMapLib.SearchInfoWindow(map, content, {
       title  : title,      //标题
       width  : 300,             //宽度
       height : 110,              //高度
       panel  : "panel",         //检索结果面板
       enableAutoPan : true,     //自动平移
       searchTypes   :[
        BMAPLIB_TAB_SEARCH,   //周边检索
        BMAPLIB_TAB_TO_HERE,  //到这里去
        BMAPLIB_TAB_FROM_HERE //从这里出发
       ]
      });

    // 创建地址解析器实例
    var myGeo = new BMap.Geocoder();
    // 将地址解析结果显示在地图上,并调整地图视野
    myGeo.getPoint(address, function (point) {
      if (point) {
        map.centerAndZoom(point, zoom);
        marker = new BMap.Marker(point);
        // 创建标注
        map.addOverlay(marker);
        // 将标注添加到地图中
        //marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
        marker.addEventListener("click", function () {
          searchInfoWindow.open(marker);
          /*this.openInfoWindow(infoWindow);
          //图片加载完毕重绘infowindow
          document.getElementById('map-show-img').onload = function () {
            infoWindow.redraw();
            //防止在网速较慢，图片未加载时，生成的信息框高度比图片的总高度小，导致图片部分被隐藏
          };*/
        });
      } else {
        alert("您选择地址没有解析到结果!");
      }
    }, city);
  });

  /*
   * 产品基本资料缩略图点击
   */
   initProductPreview();


  /*
   * 主导航开关
   * 移动端布局时的导航菜单
   */
  $(".nav-toggle").on("click", function () {
    $(".main-nav-wrap").toggleClass("active");
    $(".overlay .white").toggleClass("active");
  });
  $(".main-nav-wrap").on("click", function (event) {
    if ($(this).hasClass("active") && this == event.target) {
      $(".main-nav-wrap").removeClass("active");
      $(".overlay .white").removeClass("active");
    }
  });

  /*
   * gallery详情组件
   * 如产品详情的图集
   */
  $('[data-toggle="gallery"]').on('click', 'a', function (event) {
    var _slideContainer = $(event.delegateTarget).data('target');
    $(_slideContainer).addClass('active')
    var slider = $(_slideContainer).children('.flexslider');
    var index = $(this).closest('li').index();
    var vars = slider.data('flexslider').vars;
    var animationSpeed = vars.animationSpeed;
    slider.data('flexslider').vars.animationSpeed = 0;
    slider.flexslider(index);
    slider.data('flexslider').vars.animationSpeed = animationSpeed;
    return false;
  });
  //退出图集组件
  $(".gallery-photos > .btn").on('click', function () {
    $(this).closest('.gallery-photos').removeClass('active');
  });

  /*
   * 页面滚动组件
   * 在一些页面中（如产品详情页）中有使用到
   */
  $("[data-toggle='scroll']").on("click", "[data-target^='#']", function (event) {
    var traget = $(this).data("target");
    $.scrollTo($(traget).offset().top - 100, 1000, {
      easing: 'easeInOutExpo'
    });
    //console.log(this);
    event.stopPropagation();
    return false;
  });

  /*
   * 产品过滤器
   * 异步加载数据时可用，如果是刷新页面加载数据，则此方法无意义
   */
  $("#products-filter").on("click", "a", function () {
    productFilter($(this));
  });
  $(document).on("click", function (event) {
    if ($(event.target).closest("#products-filter").length == 0) {
      $('#products-filter').collapse("hide");
    }
  });

  /*
   * jQueryValidator设置
   * 在注册、重置密码等所有表单中有用到
   */
  $.validator.setDefaults({
      //debug:true
    });
    //添加自定义验证规则，手机号码
  $.validator.addMethod('phonenum', function (value, element, params) {
    var phonenum = /^[0-9]{11}$/;
    return this.optional(element) || (phonenum.test(value));
  });
  //添加自定义验证规则，短信验证码
  // $.validator.addMethod('smscode', function (value, element, params) {
  //   var smscode = /^[0-9]{6}$/;
  //   return this.optional(element) || (smscode.test(value));
  // });

  /*
   * 窗口resize事件
   *
   */
  $(window).resize(function () {
    videoLayout();
    contain();
    if( $(".flexslider.flexslider-grid").length > 0 && typeof delayResize === "undefined" ){
      delayResize = setTimeout(function(){
        var gridSize = getGridSize();
        $(".flexslider.flexslider-grid").each(function () {
          var flexslider = $(this).data("flexslider");
          flexslider.vars.minItems = gridSize;
          flexslider.vars.maxItems = gridSize;
        });
        // console.log("gridSize:"+gridSize,"这里flexslider是否需要内部刷新？");
        $(window).trigger('resize');
        // console.log('clearTimeout');
        delayResize = undefined;
      },500);
    }
  }).trigger('resize');


  /*
   * 异步加载model组件
   * 为了增加HTML和JS的复用性，模态组件的内容由接口返回
   */

  $("[data-toggle='dynamicModel']").on("click", function () {
    var that = $(this),
      url = that.data("api"),
      id = that.data("id"),
      params = {
        id: id
      },
      cont = $("#dynamicModel"),
      type = that.data("type");

    if (!url || !type) {
      alert("无效的data-api或data-type");
    }
    //console.log(url,params);
    $.ajax({
      dataType: type,
      url: url + '?r=' + Math.random(),
      data: params,
      success: function (data) {
        if (type === 'json') {
          alert("直接返回JSON成功，但未做下一步处理");
        }
        var element = (type === 'json') ? data.data.html : data;
        //成功返回数据后将content填充到模态内
        cont.find('.modal-content').html(element);
        //modal显示
        cont.modal();
      }
    });

    return false;
  });

  /*
   * 用户中心，删除我的收藏
   * 1、API接口请换成真实的
   * 2、需要传入什么参数自行加在params中
   */
  $("#myLoves").on("click", "button.close", function () {
    removeMyLoves($(this))
  });
  /*
   * 产品详情页收藏/删除产品
   * 1、API接口请换成真实的
   * 2、需要传入什么参数自行加在params中,默认传入pid
   */
  $(".love-btns").hover(function () {
    //显示提示
    $(this).find("a:visible").tooltip("show");
  }, function () {
    //隐藏提示
    $(this).find("a:visible").tooltip("hide");
  }).on("click", "a", function () {
    addMoveFav($(this));
  });



  /*
   * 产品点赞接口
   * 1、是否点过赞的用户不可再点？这个请问张志军
   */
  $(".up-btn").not('.disable').on("click",function(){
    var that = $(this);
    var params = {
      pid: that.parent().data("pid")
    };
    //向接口发送请求
    $.getJSON(window.apis.up + "?r=" + Math.random(), params, function (json) {
      that.addClass("disable");
      that.next().text(json.data.ups);
    });
    return false;
  });

  //服务端添加的代码由此注入
  if( typeof window.customFunction === "function"){
    window.customFunction();
  }

});




var delayResize = undefined;

var getGridSize = function () {
  return ($(window).width() < 768) ? 2 :
    ($(window).width() < 1201) ? 3 : 4;
}

var videoLayout = function () {
  $(".video-wrap").each(function () {
    var that = $(this),
      w = that.width(),
      r = parseFloat(that.data("ratio"));
    that.height(w * r);
  });
}

//包含显示图片（就是铺满容器但不裁切）
var contain = function () {
  //console.log('contain resize!');
  $('.contain-wrap > img').each(function () {
    var _w = parseInt($(this).data('width'));
    var _h = parseInt($(this).data('height'));
    var area = $(this).parent();
    var areaW = area.innerWidth();
    var areaH = area.innerHeight();
    $(area).css("line-height", areaH + "px");
    if (!_w) {
      return;
    }
    if (_w < areaW && _h < areaH){
      $(this).removeAttr("style");
      return;
    }
    var sourceW = _w;
    var sourceH = _h;
    var scale;
    if (areaW / areaH < sourceW / sourceH) {
      scale = areaW / sourceW;
    } else {
      scale = areaH / sourceH;
    }

    $(this).width(sourceW * scale);
  });
}

//异步加载图片slider，在滚动到目标时加载图片
var renderPreview = function (slider) {
  var slider = slider;
  var targetID = slider.animatingTo;
  var targetLi = slider.slides[targetID];
  var path = $(targetLi).data('src') || $(targetLi).find('[data-src]').eq(0).data('src');
  if (!path) {
    return;
  }

  var cont = $(targetLi).data('src') ? $(targetLi) : $(targetLi).find('[data-src]').eq(0);
  var img = new Image();
  $(img).appendTo(cont).fadeOut(0);
  img.onload = function () {
    this.onload = null;
    var _w = img.naturalWidth || this.width;
    var _h = img.naturalHeight || this.height;
    //console.log(_w, _h);
    $(this).attr('data-width', _w).attr('data-height', _h).delay(50).fadeIn(500);
    $(this).closest('[data-src]').removeAttr('data-src').data('src', '').addClass('in');
    contain();
  };
  img.src = path;
}


//短信初始化
var initSMS = function () {
  var maxTime = 60;
  var nowTime = maxTime;
  var timer;
  var phonenum = /^[0-9]{11}$/;
  //发送验证短信
  $('#sendCodeBtn').on("click", function () {
    var that = $(this);
    var phone = $("#phone").val();
    var params = {};

    //如果表单里有手机号码输入框，但用户未填写手机号码，则弹窗并中止
    if (phone && !phonenum.test(phone)) {
      alert("无效的手机号码");
      return;
    }

    if (phone) {
      params.phone = phone;
    }

    that.attr("disabled", "true");


    $.ajax({
      dataType: "json",
      url: window.apis.smscode + '?r=' + Math.random(),
      data: params,
      success: function (json) {
        //        console.log("code send done!");
        alert('DEBUG,短信发送成功,SMSCode:' + json.data.msmCode);
        console.log(json.data.msmCode);
      },
      error: function (error) {
        alert('DEBUG,短信发送失败');
        console.log(error);
      }
    });

    timer = setInterval(function () {
      if (nowTime > 0) {
        nowTime--;
        that.children("span").text(' (' + nowTime + ')');
      } else {
        that.removeAttr("disabled");
        that.html("重新发送<span></span>");
        clearInterval(timer);
        nowTime = maxTime;
      }
    }, 1000);
  });
}

//初始化产品缩略图（产品详情页使用）
var initProductPreview = function () {

  var container = $(".product-description");
  if( !container ){
    return;
  }

  var thumbs = container.find(".thumbs img").each(function(index, el) {
    $(this).data("id",index);
  });
  var images = container.find(".images");
  var nextArrow = container.find(".next");
  var prevArrow = container.find(".prev");
  var description = container.find(".description");
  var currentID = 0;
  var total = thumbs.length;

  var prevImage = function(){
    if(currentID == 0){
      currentID = total-1;
    }else{
      currentID--;
    }
    // console.log("prev:",currentID);
    preloadImage(currentID);
  }
  var nextImage = function(){
    if(currentID == total-1){
      currentID = 0;
    }else{
      currentID++;
    }
    // console.log("next:",currentID);
    preloadImage(currentID);
  }
  var jumpImage = function(ID){
    currentID = ID;
    // console.log("jump:",currentID);
    preloadImage(currentID);
  }
  var preloadImage = function(ID){
    var src = thumbs.eq(currentID).data("src");
    // console.log(src);
    if( !src ){
      return;
    }
    if( $("html").hasClass("touch") ){
      container.find(".control i").fadeOut();
    }

    updateThumbs();
    images.addClass('loading');
    description.fadeOut();
    var img = new Image();
    img.onload = function () {
      var that = $(this)
      updateImage(that);
      updateDescription();
      updateThumbs();
    }
    img.src = src;
  }
  var updateImage = function(img){
    images.removeClass('loading');
    img.hide().appendTo(images).fadeIn(500, clearOld);
  }
  var updateDescription = function(){
    var text = thumbs.eq(currentID).data("info");
    if( text ){
      description.text(text).fadeIn();
    }
  }
  var updateThumbs = function(){
    thumbs.removeClass('active');
    thumbs.eq(currentID).addClass('active');
  }
  var clearOld = function(){
    images.find("img").eq(0).remove();
  }

  //首次更新
  if ( thumbs.length <= 1 ){
    container.find(".control").remove();
    return;
  }

  updateDescription();
  updateThumbs();

  /*
   * 产品详情预览缩略图切换
   */
  thumbs.on('click', function () {
    var id = $(this).data("id");
    jumpImage(id);
  });

  /*
   * 产品详情预览左右切换
   */
  container.find(".control").on("click", function () {
    if( $(this).hasClass('prev') ){
      prevImage();
    }else{
      nextImage();
    }
  });
}

function addMoveFav(element){
    var that = element;
    //点击收藏或移除
    var params = {
      pid: that.parent().data("pid")
    };
    var isAddlove = element.hasClass("addlove");
    var api = isAddlove ? window.apis.addlove : window.apis.removelove;
    var msg = isAddlove ? "已收藏！" : "已取消收藏！";
    //向接口发送请求
    $.getJSON(api + "?r=" + Math.random(), params, function (data) {
      that.hide().siblings("a").show();
      alert(msg)
    });
    return false;
  };

function removeMyLoves(element) {
    var that = element;
    var p = that.closest("li");
    var pid = p.data("pid");
    var params = {
      pid: pid
    };
    p.remove();
    $.getJSON(window.apis.removelove + "?r=" + Math.random(), params, function (data) {
      alert("成功移除！")
    });
}

function productFilter(element) {
    var that = element;
    //给自己添加active样式，并且给兄弟元素去除active样式
    that.addClass("active").siblings().removeClass("active");
    //触发折叠
    $('#products-filter').collapse("toggle");
    return false;
}
